package top.go2do.auth.business.user.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.go2do.auth.business.user.module.LoginCheckBO;
import top.go2do.auth.business.user.module.LoginResultVO;
import top.go2do.common.module.UserPO;
import top.go2do.auth.exception.AuthErrorCode;
import top.go2do.auth.exception.AuthException;
import top.go2do.common.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/4/1 17:03
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean loginCheck(LoginCheckBO checkBO) {
        return userService.checkUsernameAndPassword(checkBO);
    }

    @Override
    public LoginResultVO generateLoginResult(Long userId){
        Map payload = new HashMap(2);
        payload.put(JwtUtils.KEY_USER_ID, userId);
        String accessToken = jwtUtils.generateAccessToken(payload);
        String refreshToken = jwtUtils.generateRefreshToken(payload);
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setAccessToken(accessToken);
        loginResultVO.setRefreshToken(refreshToken);
        return loginResultVO;
    }

    @Override
    public LoginResultVO toLoginWithToken(LoginCheckBO checkBO) {
        UserPO userPO = userService.findByUsername(checkBO.getUsername());
        boolean checkPassword = userService.checkUsernameAndPassword(checkBO, userPO);
        if (!checkPassword) {
            throw new AuthException(AuthErrorCode.USER_PASSWORD_ERROR);
        }
        return generateLoginResult(userPO.getUserId());
    }

    @Override
    public UserPO findByAppIdAndUserName(String appId, String username) {
        return userService.findByAppIdAndUsername(appId, username);
    }

}
